const PublicIp = require('nodejs-publicip')
const Log = require('./log-util')
const topic = "get-ip.js"

const ipFetch = async () => await new PublicIp().queryPublicIPv4Address()

const getIP = async () => {
    let ip
    try {
        ip = await ipFetch()
    } catch (e) {
        let errorCount = 1
        let isError = true
        while (isError && errorCount < 3) {
            try {
                isError = false
                ip = await ipFetch()
            } catch (e) {
                isError = true
                errorCount ++
            }
        }

        if (isError === true) {
            Log.error(topic, "Failed to Fetch IP address. Caused by " + e)
            return '127.0.0.1'
        }
    }
    return ip;
}

async function logIP() {
    const ip = await getIP();
    console.log(ip)
}

module.exports = getIP


